//: [Previous](@previous)

import Foundation
import UIKit
import XCPlayground


var str = "Hello, playground"

/**
 //: 
 ###    单例，GCD，Sequences和Generators,运算符重载
 ***/
//泛型函数
//实现自定义SequenceType协议方法，注意观察Carousel中两个generate实现不同之处和结果
//GeneratorType迭代类型，next->T?返回下一个元素，直到没有下一个元素
struct CarouselGenerator<T>: GeneratorType {
    var carousel: Carousel<T>
    var iterations: Int = 0
    var done: Bool      = false
    
    init(carousel: Carousel<T>) {
        self.carousel = Carousel<T>(items: carousel.items, initialPosition: carousel.currentPosition)
    }
    
    mutating func next() -> T? {
        if done {
            preconditionFailure("CarouselGenerator already completed")
        }
        if iterations >= carousel.count {
            done = true
            return nil
        }
        iterations += 1
        return carousel.next()
    }
}

//Sequences和Generators
//SequenceType序列化，其中有生成迭代对象的方法。
class Carousel<T>: SequenceType {
    var items = [T]()
    var currentPosition = 0
    
    var count: Int {
        return items.count
    }
    
    var isEmpty: Bool {
        return items.isEmpty
    }
    
    convenience init(items: [T], initialPosition: Int = 0) {
        self.init()
        self.items = items
        currentPosition = initialPosition
    }
    
    func append(item: T) {
        items.append(item)
    }
    
    func next() -> T? {
        if self.isEmpty {
            return nil
        }
        
        let nextItem = self[currentPosition]
        currentPosition = (currentPosition + 1) % self.count
        
        return nextItem
    }
    
    //附属属性
    subscript(position: Int) -> T? {
        if self.isEmpty {
            return nil
        }
        return items[position % self.count]
    }
    
    //MARK: SequenceType协议
    //    func generate() -> IndexingGenerator<Array<T>> {
    //        return items.generate()
    //    }
    func generate() -> CarouselGenerator<T> {
        return CarouselGenerator<T>(carousel: self)
    }
}

//: 1。以记录的形式实现一个简单的演员/电影数据库。创建两个版本。第一个版本中所有的类型都是分开的（不需要嵌套),第二个版本则使用嵌套类型。比较两个版本，哪个版本可读性以及可维护性更好
struct RecordType01 {
    var name: String
    var filmName: String
}

struct  RecordType02 {
    var acotr:  String
    struct Filmer {
        var name: String
    }
    var filmer : Filmer
    
}

let actor01 = RecordType01(name: "zmj", filmName: "我的特工爷爷")
let actor02 = RecordType01(name: "wjl", filmName: "十面埋伏")

let record03 = RecordType02(acotr: "zmj", filmer: RecordType02.Filmer(name: "我的特工爷爷"))
let record04 = RecordType02(acotr: "wjl", filmer: RecordType02.Filmer(name: "十面埋伏"))

//: 2.创建一个伪单例对象，用于管理你的App主题。实现一些基于设备的类型和Size获取颜色、字体和其他属性的方法
class AppConfigure {
    //伪单例对象属性，类属性
    class var defaultAppConfigure: AppConfigure {
        //嵌套结构体，然后使用结构结构体的静态（或者全局）变量时，Swift会用dispatch_once方法来初始化变量。这样就保证该变量智慧别初始化一次
        struct  Statics {
            static var instance = AppConfigure()
        }
        return Statics.instance
    }
    func size() -> CGSize {
        return UIScreen.mainScreen().bounds.size
    }
    func apple_type() -> UIUserInterfaceIdiom {
        return UIDevice.currentDevice().userInterfaceIdiom
    }
    func iphoneType() -> String {
        let size = self.size()
        if CGSizeEqualToSize(size, CGSizeMake(320, 480)) {
            return "4"
        } else if CGSizeEqualToSize(size, CGSizeMake(320, 568)) {
            return "5"
        } else if CGSizeEqualToSize(size, CGSizeMake(375, 667)) {
            return "6"
        } else if CGSizeEqualToSize(size, CGSizeMake(414, 736)) {
            return "6p"
        }
        return "3"
    }
    func ipadType() -> String {
        let size = self.size()
        if CGSizeEqualToSize(size, CGSizeMake(768, 1024)) {
            let scale = UIScreen.mainScreen().scale
            if scale == 1.0 {
                return "ipad"
            } else if scale == 2.0 {
                return "ipad air"
            }
        }
        return "ipad pro"
    }
    func apple_Type_name() -> (type: String, name: String) {
        let appletype = self.apple_type()
        switch appletype {
        case .Phone:
            return ("iPhone", self.iphoneType())
        case .Pad:
            return ("ipad", self.ipadType())
        case .TV:
            return ("TV", "1.0")
        case .CarPlay:
            return ("CarPlay", "1.0")
        case .Unspecified:
            return ("unknowed", "0.0")
        }
    }
    
    //MARK  默认设置
    func defaultColor() -> UIColor {
        let typeName = apple_Type_name()
        var color : UIColor
        switch typeName{
        case ("iPhone", let name):
            switch name {
            case "4":
                color = UIColor.redColor()
            case "5":
                color = UIColor.greenColor()
            case "6" :
                color = UIColor.grayColor()
            case "6p":
                color = UIColor.brownColor()
            default:
                color = UIColor.cyanColor()
            }
        case ("iPad", let name):
            switch name {
            case "ipad":
                color = UIColor.blueColor()
            case "ipad air":
                color = UIColor.blackColor()
            default:
                color = UIColor.darkGrayColor()
            }
        default:
            color = UIColor.darkTextColor()
        }
        return color
    }
    
    func defaultFont() -> UIFont {
        let typeName = apple_Type_name()
        var fontSize = 13.0
        switch typeName{
        case ("iPhone", let name):
            switch name {
            case "6" :
                fontSize = 15.0
            case "6p":
                fontSize = 17.0
            default:
                fontSize = 13.0
            }
        case ("iPad", let name):
            switch name {
            case "ipad":
                fontSize = 21.0
            case "ipad air":
                fontSize = 23.0
            default:
                fontSize = 25.0
            }
        default:
            fontSize = 13.0
        }
        return UIFont.systemFontOfSize(CGFloat(fontSize))
    }
    
    func defaultImage() -> UIImage {
        return UIImage.init(imageLiteral: "好吗")
    }
}

let defaultApp = AppConfigure.defaultAppConfigure
defaultApp.defaultFont()
defaultApp.defaultColor()


//3.0使用GCD方法在后台下载一个网络图片，下载完成后，显示该图片。实现如下特性可获得额外的加分：创建缓存管理，以减少不必要的重复下载
//https://camo.githubusercontent.com/68ce8767f20b6a40f2a695c56396d30234363431/687474703a2f2f73756e7365746c616b65736f6674776172652e636f6d2f73697465732f64656661756c742f66696c65732f475055496d6167654c6f676f2e706e67
//https://github.com/mrackwitz/MRProgress/raw/master/Images/screenshot_004_2.jpg
//https://github.com/mrackwitz/MRProgress/raw/master/Images/screenshot_005_2.jpg
//https://github.com/mrackwitz/MRProgress/raw/master/Images/screenshot_006_2.jpg
//https://github.com/mrackwitz/MRProgress/raw/master/Images/screenshot_007_2.jpg
//https://github.com/jathu/UIImageColors/raw/master/preview.png
//https://github.com/lilei644/LLSlideMenu/raw/master/Preview/LLSlideMenuPreview.gif
//https://raw.githubusercontent.com/me-abhinav/NumberMorphView/dev/sample.gif
//https://camo.githubusercontent.com/231b1f75305c55093c9f2f8e1d78a7e47b2ae401/68747470733a2f2f7261772e6769746875622e636f6d2f4d656c6c6f6e674c61752f414d416e696d617465644e756d6265722f6d61737465722f53637265656e73686f74732f73637265656e73686f742e676966
//https://github.com/PhamBaTho/BTNavigationDropdownMenu/raw/master/Assets/Demo.gif
let urls = ["https://camo.githubusercontent.com/68ce8767f20b6a40f2a695c56396d30234363431/687474703a2f2f73756e7365746c616b65736f6674776172652e636f6d2f73697465732f64656661756c742f66696c65732f475055496d6167654c6f676f2e706e67",
            "https://github.com/mrackwitz/MRProgress/raw/master/Images/screenshot_004_2.jpg",
            "https://github.com/mrackwitz/MRProgress/raw/master/Images/screenshot_005_2.jpg",
            "https://github.com/mrackwitz/MRProgress/raw/master/Images/screenshot_006_2.jpg",
            "https://github.com/mrackwitz/MRProgress/raw/master/Images/screenshot_007_2.jpg",
            "https://github.com/jathu/UIImageColors/raw/master/preview.png",
            "https://camo.githubusercontent.com/231b1f75305c55093c9f2f8e1d78a7e47b2ae401/68747470733a2f2f7261772e6769746875622e636f6d2f4d656c6c6f6e674c61752f414d416e696d617465644e756d6265722f6d61737465722f53637265656e73686f74732f73637265656e73686f742e676966"]

class PracticeCell: UICollectionViewCell {
    var width: CGSize
    var imageView = UIImageView()
    var titleLab = UILabel()
    
    override init(frame: CGRect) {
        width = frame.size
        super.init(frame: frame)
        imageView.frame = CGRectMake(0, 0, width.width, width.width)
        titleLab.frame = CGRectMake(0, width.width, width.width, width.height - width.width)
        self.contentView.addSubview(imageView)
        self.contentView.addSubview(titleLab)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

let cache = NSCache.init()
extension UIImageView {
    func setImageWithUrl(url: String) {
        if url.characters.count == 0 {
            return
        }
        let image = cache.objectForKey(url)
        guard let lastImage = image else {
            let urls = NSURL.init(string: url)
            let task = NSURLSession.sharedSession().dataTaskWithURL(urls!, completionHandler: { (data, response, error) in
                if error == nil {
                    if let lastData = data {
                        cache .setObject(lastData, forKey: url)
                        self.image = UIImage.init(data: lastData)
                    }
                }
            })
            task.resume()
            return
        }
        self.image = lastImage as? UIImage
    }
}

class CollectionViewDelegate: NSObject, UICollectionViewDelegate, UICollectionViewDataSource {
    var collectionView: UICollectionView
    init(collectionView: UICollectionView) {
        self.collectionView = collectionView
        super.init()
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = UIColor.whiteColor()
        self.collectionView.registerClass(PracticeCell.self, forCellWithReuseIdentifier: "cellIndexPath")
        self.collectionView.reloadData()
    }
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView .dequeueReusableCellWithReuseIdentifier("cellIndexPath", forIndexPath: indexPath) as! PracticeCell
        cell.titleLab.text = urls[indexPath.row]
        cell.imageView.setImageWithUrl(urls[indexPath.row])
        cell.backgroundColor = UIColor.greenColor()
        return cell
    }
    
}

let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSizeMake(200, 300)
layout.minimumLineSpacing = 5
layout.minimumInteritemSpacing = 5
let collectionView = UICollectionView(frame: CGRectMake(0, 0, 320, 568), collectionViewLayout: layout)
collectionView.contentInset = UIEdgeInsetsMake(5, 5, 5, 5)
let dataDelegate = CollectionViewDelegate.init(collectionView: collectionView)

XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = collectionView



//: [Next](@next)
